﻿using System;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.Events;

namespace Elvex
{
    public class TCPConnection
    {
        public TCPConnection()
        {
            Application.quitting += Close;
        }

        ~TCPConnection()
        {
            Application.quitting -= Close;
        }

        public UnityEvent OnError { get; } = new UnityEvent();

        public UnityEvent<byte[]> OnReceive { get; } = new UnityEvent<byte[]>();

        private Socket m_socket = null; 

        private TCPSession m_session = null;

        public bool Connect(string host, int port)
        {
            if( null != m_socket)
            {
                return false;
            }

            //IPHostEntry hostEntry = Dns.GetHostEntry(host);
            m_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            m_socket.Connect(host, port);
            //m_socket.Connect(hostEntry.AddressList, port);
            if(m_socket.Connected)
            {
                m_session = new TCPSession(m_socket);
                m_session.OnError.AddListener(OnError.Invoke);
                m_session.OnReceive.AddListener(OnReceive.Invoke);
            }
            return m_socket.Connected;
        }

        public void Close()
        {
            if (null != m_socket)
            {
                if (m_socket.Connected)
                {
                    m_socket.Close();
                }
                m_socket = null;
            }
            OnError.RemoveAllListeners();
            OnReceive.RemoveAllListeners();
        }

        public bool Deliver(byte[] buffer)
        {
            return m_session.Deliver(buffer);
        }
    }
}
